#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

using System.Threading;
using UnityEngine;

namespace EntityKit.Runtime
{
    [DisallowMultipleComponent]
    public sealed class AsyncDestroyTrigger : MonoBehaviour
    {
        private bool _awakeCalled = false;
        private bool _called = false;
        private CancellationTokenSource _cancellationTokenSource;

        public CancellationToken CancellationToken
        {
            get
            {
                if (_cancellationTokenSource == null)
                {
                    _cancellationTokenSource = new CancellationTokenSource();
                }

                if (!_awakeCalled)
                {
                    // 确保组件已正确初始化
                    Awake();
                }

                return _cancellationTokenSource.Token;
            }
        }

        private void Awake()
        {
            if (_awakeCalled) return;
            _awakeCalled = true;
        }

        private void OnDestroy()
        {
            if (_called) return;
            _called = true;

            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            _cancellationTokenSource = null;
        }
    }
}